package cn.abcsys.cloud.devops.pipeline.service.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.abcsys.cloud.devops.pipeline.common.Constant;
import cn.abcsys.cloud.devops.pipeline.common.GridBean;
import cn.abcsys.cloud.devops.pipeline.common.JenkinsItem;
import cn.abcsys.cloud.devops.pipeline.common.Status;
import cn.abcsys.cloud.devops.pipeline.common.SystemConfig;
import cn.abcsys.cloud.devops.pipeline.common.Type;
import cn.abcsys.cloud.devops.pipeline.controller.PipelineController;
import cn.abcsys.cloud.devops.pipeline.core.ImageCore;
import cn.abcsys.cloud.devops.pipeline.core.PipelineCore;
import cn.abcsys.cloud.devops.pipeline.dao.ImageMapper;
import cn.abcsys.cloud.devops.pipeline.dao.TaskEventMapper;
import cn.abcsys.cloud.devops.pipeline.dao.TaskMapper;
import cn.abcsys.cloud.devops.pipeline.entity.Image;
import cn.abcsys.cloud.devops.pipeline.entity.Task;
import cn.abcsys.cloud.devops.pipeline.entity.TaskEvent;
import cn.abcsys.cloud.devops.pipeline.message.MessagePublisher;
import cn.abcsys.cloud.devops.pipeline.model.ImageModel;
import cn.abcsys.cloud.devops.pipeline.model.TaskModel;
import cn.abcsys.cloud.devops.pipeline.service.PipelineService;
import cn.abcsys.cloud.devops.pipeline.util.Result;
@Component
public class PipelineServiceImpl implements PipelineService {
	private static final Logger LOGGER = Logger.getLogger(PipelineController.class);
	@Autowired
	private PipelineCore pipelineCore;
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private TaskEventMapper taskEventMapper;
	@Autowired
	private SystemConfig systemConfig;
	@Autowired
	private ImageCore imageCore;
	@Autowired
	private MessagePublisher publisher;
	@Autowired
	private ImageMapper imageMapper;
	/**
	 * 创建成功返回任务对象
	 */
	@Override
	public Result createTask(JSONObject paramIn) {
		String respositry_type = paramIn.getString("repository_type");
		if(Type.REPOSIROETY.git.name().equals(respositry_type)){
			
		}else if(Type.REPOSIROETY.svn.name().equals(respositry_type)){
			return new Result(false, "暂不支持svn");
		}else if(Type.REPOSIROETY.gitLab.name().equals(respositry_type)){
			return new Result(false, "暂不支持gitLab");
		}else{
			return new Result(false, "暂不支持此类型源码仓库");
		}
		try {
			Task task = taskMapper.getTaskByProjectId(paramIn.getInteger("projectId"));
			if(null!=task){
				return new Result(false, "已存在此应用");
			}
		} catch (SQLException e1) {
			return new Result(false, e1.getMessage());
		}
		Task task = new Task();
		String userName = paramIn.getString("userName");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String jobName = userName+"_"+paramIn.getString("projectName")+"_"+sdf.format(new Date());
		paramIn.put("jenkinsJobName", jobName);
		if(systemConfig.getJenkinsWorkspace().endsWith("/")){
			task.setJenkinsBuildPath(systemConfig.getJenkinsWorkspace()+jobName);
		}else{
			task.setJenkinsBuildPath(systemConfig.getJenkinsWorkspace()+"/"+jobName);
		}
		task.setBranckSpecifier(paramIn.getString("branchSpecifier"));
		task.setRepositoryType(respositry_type);
		task.setBuildTimes(0);
		task.setJenkinsJobName(jobName);
		task.setJenkinsPwd(systemConfig.getJenkinsPwd());
		task.setJenkinsUrl(systemConfig.getJenkinsUrl());
		task.setJenkinsUser(systemConfig.getJenkinsUser());
		task.setProjectId(paramIn.getInteger("projectId"));
		task.setRepositoryUrl(paramIn.getString("repositoryUrl"));
		task.setTaskCreator(paramIn.getInteger("taskCreator"));
		task.setTaskName(jobName);
		task.setTaskStatus((byte)Status.COMMON.NORMAL.ordinal());
		task.setTaskStage(paramIn.getByte("taskStage"));
		task.setClairEnable(paramIn.getByte("clairEnable"));
		task.setSonarEnable(paramIn.getByte("sonarEnable"));
		task.setDockerfile(paramIn.getString("Dockerfile"));
		task.setBuildImageInJenkins((byte)(paramIn.getByte("buildImageInJenkins")==null?0:1));
		task.setPushImageInJenkins((byte)(paramIn.getByte("pushImageInJenkins")==null?0:1));
		task.setRegistryUrl(paramIn.getString("registryUrl"));
		task.setRegistryId(paramIn.getInteger("registryId"));
		task.setProjectName(paramIn.getString("projectName"));
		task.setEnvId(paramIn.getInteger("envId"));
		try {
			taskMapper.insertTask(task);
			paramIn.put("taskId", task.getTaskId());
			//记录创建任务事件
			this.createTaskEvent(Constant.CREATE_TASK,Constant.SUCCESS_CHN,task.getTaskId(),1,0,null,(byte)0);
			if(paramIn.getByte("taskStage")<=Constant.REPOSITORY_STEP){
				//源码添加到jenkins中
				this.createRepositoryItem(paramIn);
			}else if(paramIn.getByte("taskStage")==Constant.UPLOAD_APP_PACKAGE_STEP){
				//从应用包上传开始执行
				this.uploadAppItem(paramIn);
			}else if(paramIn.getByte("taskStage")==Constant.UPLOAD_IMAGE_STEP){
				//从镜像上传开始执行
				this.uploadImageItem(paramIn);
			}
			paramIn.put("taskId", task.getTaskId());
			paramIn.put("taskName",task.getTaskName());
			paramIn.put("jenkinsBuildNumber",0);
			paramIn.put("sonarBuild",0);
			paramIn.put("makeImage",0);
			paramIn.put("imageClair",0);
			paramIn.put("pushImage",0);
//			List<TaskEvent> events = taskEventMapper.selectEventsByTaskId(task.getTaskId());
//			paramIn.put("events",JSONArray.fromObject(events));
			return new Result(true,paramIn,"创建pipeline成功");
		} catch (SQLException e) {
			LOGGER.error( "创建pipeline失败:"+e.getMessage());
			return new Result(false, "创建pipeline失败:"+e.getMessage());
		}
	}
	/**
	* @Title: updateTask 
	* @Description: 更新任务 
	* @param @param paramIn
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	@Override
	public Result updateTask(JSONObject paramIn) {
		String respositry_type = paramIn.getString("repository_type");
		if(Type.REPOSIROETY.git.name().equals(respositry_type)){
			
		}else if(Type.REPOSIROETY.svn.name().equals(respositry_type)){
			return new Result(false, "暂不支持svn");
		}else if(Type.REPOSIROETY.gitLab.name().equals(respositry_type)){
			return new Result(false, "暂不支持gitLab");
		}else if(null!=respositry_type){
			return new Result(false, "暂不支持此类型源码仓库");
		}
//		String userName = paramIn.getString("userName");
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//		String jobName = userName+"_"+paramIn.getString("projectName")+"_"+sdf.format(new Date());
//		paramIn.put("jenkinsJobName", jobName);
		Task task = new Task();
		task.setTaskId(paramIn.getInteger("taskId"));
		task.setBranckSpecifier(paramIn.getString("branchSpecifier"));
		task.setRepositoryType(respositry_type);
//		task.setJenkinsBuildPath(systemConfig.getJenkinsWorkspace()+"/"+jobName);
//		task.setJenkinsJobName(jobName);
		task.setRepositoryUrl(paramIn.getString("repositoryUrl"));
//		task.setTaskName(jobName);
		task.setTaskStatus((byte)Status.COMMON.NORMAL.ordinal());
		task.setTaskStage(paramIn.getByte("taskStage"));
		task.setClairEnable(paramIn.getByte("clairEnable"));
		task.setSonarEnable(paramIn.getByte("sonarEnable"));
		task.setDockerfile(paramIn.getString("Dockerfile"));
		task.setBuildImageInJenkins((byte)(paramIn.getByte("buildImage")==null?0:1));
		task.setPushImageInJenkins((byte)(paramIn.getByte("pushImage")==null?0:1));
		try {
			taskMapper.updateTask(task);
			paramIn.put("taskId", task.getTaskId());
			//记录创建任务事件
			this.createTaskEvent(Constant.MOIDFY_TASK,Constant.SUCCESS_CHN,task.getTaskId(),1,0,null,(byte)0);
			if(paramIn.getByte("taskStage")<=Constant.REPOSITORY_STEP){
				//源码添加到jenkins中
				this.createRepositoryItem(paramIn);
			}else if(paramIn.getByte("taskStage")==Constant.UPLOAD_APP_PACKAGE_STEP){
				//从应用包上传开始执行
				this.uploadAppItem(paramIn);
			}else if(paramIn.getByte("taskStage")==Constant.UPLOAD_IMAGE_STEP){
				//从镜像上传开始执行
				this.uploadImageItem(paramIn);
			}
			paramIn.put("taskName",task.getTaskName());
			List<TaskEvent> taskEvents = taskEventMapper.selectEventsByTaskId(paramIn.getInteger("taskId"));
			for(TaskEvent taskEvent:taskEvents){
				if(taskEvent.getEventStep()==Constant.JENKINS_STEP){
					paramIn.put("jenkinsBuildNumber",taskEvent.getExcuteTimes());
				}else if(taskEvent.getEventStep()==Constant.SONAR_STEP){
					paramIn.put("sonarBuild",taskEvent.getExcuteTimes());
				}else if(taskEvent.getEventStep()==Constant.MAKE_IMAGE_STEP){
					paramIn.put("makeImage",taskEvent.getExcuteTimes());
				}else if(taskEvent.getEventStep()==Constant.CLAIR_STEP){
					paramIn.put("imageClair",taskEvent.getExcuteTimes());
				}else if(taskEvent.getEventStep()==Constant.PUSH_IMAGE_STEP){
					paramIn.put("pushImage",taskEvent.getExcuteTimes());
				}
			}
			return new Result(true,paramIn,"创建pipeline成功");
		} catch (SQLException e) {
			LOGGER.error( "创建pipeline失败:"+e.getMessage());
			return new Result(false, "创建pipeline失败:"+e.getMessage());
		}
	}
	/**
	* @Title: createRepository 
	* @Description: 源码仓库
	* @param @param paramIn
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result createRepository(JSONObject paramIn){
		JenkinsItem jenkinsItem = new JenkinsItem();
		jenkinsItem.setBranch_specifier(paramIn.getString("branchSpecifier"));
		if(StringUtils.isEmpty(paramIn.getString("repositoryUrl"))){
			jenkinsItem.setRepository_url("*/master");
		}else{
			jenkinsItem.setRepository_url(paramIn.getString("repositoryUrl"));
		}
		jenkinsItem.setJenkins_user(systemConfig.getJenkinsUser());
		jenkinsItem.setJenkins_pwd(systemConfig.getJenkinsPwd());
		jenkinsItem.setJenkins_url(systemConfig.getJenkinsUrl());
		jenkinsItem.setJenkinsDaysToKeep(systemConfig.getJenkinsDaysToKeep());
		jenkinsItem.setJenkinsNumToKeep(systemConfig.getJenkinsNumToKeep());
		jenkinsItem.setMakeImage(paramIn.getByteValue("makeImage"));
		jenkinsItem.setPushImage(paramIn.getByteValue("pushImage"));
		String jobName = paramIn.getString("jenkinsJobName");
		jenkinsItem.setItem_name(jobName);
		Result result = pipelineCore.createJenkinsProject(jenkinsItem);
		return result;
	}
	/**
	* @Title: sonarScanner 
	* @Description: 源码质量检查
	* @param @param paramIn
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result sonarScanner(JSONObject paramIn){
		return new Result(true, "");
	}
	/**
	* @Title: jenkinsBuild 
	* @Description: jenkins应用构建
	* @param @param paramIn
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result jenkinsJobBuild(JSONObject paramIn){
		JenkinsItem jenkinsItem = new JenkinsItem();
		jenkinsItem.setJenkins_user(systemConfig.getJenkinsUser());
		jenkinsItem.setJenkins_pwd(systemConfig.getJenkinsPwd());
		jenkinsItem.setJenkins_url(systemConfig.getJenkinsUrl());
		jenkinsItem.setItem_name(paramIn.getString("jenkinsJobName"));
		jenkinsItem.setMakeImage(paramIn.getByteValue("makeImage"));
		jenkinsItem.setPushImage(paramIn.getByteValue("pushImage"));
		long begin = new Date().getTime()/1000;
		LOGGER.info("Jenkins build begin...");
		publisher.pushMessage(paramIn.getInteger("taskId"), "3");
		Result result = pipelineCore.buildJob(jenkinsItem);
		long end = new Date().getTime()/1000;
		LOGGER.info("Jenkins buid end. Lost time "+(end-begin)+"s");
		if(!result.isSuccess()){
			return result;
		}
		JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
		//创建源码集成事件
		this.createTaskEvent(Constant.JENKINS_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				paramIn.getInteger("taskId"),jsonObject.getIntValue("number"),end-begin,
				result.getData()==null?null:result.getData().toString(),Constant.JENKINS_STEP);
		return result;
	}
	/**
	* @Title: jenkinsBuild 
	* @Description: 构建日志输出
	* @param @param paramIn
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result jenkinsBuildConsoleOutput(JSONObject paramIn){
		JenkinsItem jenkinsItem = new JenkinsItem();
		jenkinsItem.setJenkins_user(systemConfig.getJenkinsUser());
		jenkinsItem.setJenkins_pwd(systemConfig.getJenkinsPwd());
		jenkinsItem.setJenkins_url(systemConfig.getJenkinsUrl());
		jenkinsItem.setItem_name(paramIn.getString("jenkinsJobName"));
		jenkinsItem.setNumber(paramIn.getIntValue("build_number"));
		return pipelineCore.getJobConsoleLog(jenkinsItem);
	}
	/**
	* @Title: makeImage 
	* @Description: 镜像制作
	* @param @param paramIn{ImageName,Dockerfile,targetFolder}
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result makeImage(JSONObject paramIn){
		paramIn.put("pipelineHostIp", systemConfig.getPipelineHostIp());
		paramIn.put("pipelineHostUser", systemConfig.getPipelineHostUser());
		paramIn.put("pipelineHostPwd", systemConfig.getPipelineHostPwd());
		int taskId = paramIn.getIntValue("taskId");
		long begin = new Date().getTime()/1000;
		LOGGER.info("Make image begin...");
		publisher.pushMessage(paramIn.getInteger("taskId"), "5");
		Result result = imageCore.makeImage(paramIn);
		long end = new Date().getTime()/1000;
		LOGGER.info("Make image end. Lost time "+(end-begin)+"s");
		String executeResult =null;
		if(result.getData()!=null){
			JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
			executeResult = jsonObject.getString("executeResult");
			//去除executeResult信息
//			result.setData(jsonObject.remove("executeResult"));
		}
		//创建镜像事件
		this.createTaskEvent(Constant.MAKE_IMAGE_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				taskId,0,end-begin,executeResult,Constant.MAKE_IMAGE_STEP);
		return result;
	}
	/**
	* @Title: clairScanner 
	* @Description: 镜像安全扫描
	* @param @param paramIn{imageUuid}
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result clairScanner(JSONObject paramIn){
		paramIn.put("pipelineHostIp", systemConfig.getPipelineHostIp());
		paramIn.put("pipelineHostUser", systemConfig.getPipelineHostUser());
		paramIn.put("pipelineHostPwd", systemConfig.getPipelineHostPwd());
		paramIn.put("imageClairLogsPath", systemConfig.getImageClairLogsPath());
		int taskId = paramIn.getIntValue("taskId");
		LOGGER.info("Clair scanner image begin...");
		publisher.pushMessage(paramIn.getInteger("taskId"), "7");
		long begin = new Date().getTime()/1000;
		Result result = imageCore.scanImage(paramIn);
		long end = new Date().getTime()/1000;
		LOGGER.info("Clair scanner image end. Lost time "+(end-begin)+"s");
		this.createTaskEvent(Constant.CLAIR_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				taskId,0,end-begin, result.getData()==null?null:result.getData().toString(),Constant.CLAIR_STEP);
		return result;
	}
	/**
	* @Title: clairScanner 
	* @Description: 镜像安全扫描日志查询
	* @param @param paramIn{imageUuid}
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	public Result clairLogs(JSONObject paramIn){
		paramIn.put("pipelineHostIp", systemConfig.getPipelineHostIp());
		paramIn.put("pipelineHostUser", systemConfig.getPipelineHostUser());
		paramIn.put("pipelineHostPwd", systemConfig.getPipelineHostPwd());
		paramIn.put("imageClairLogsPath", systemConfig.getImageClairLogsPath());
		paramIn.put("imageUuid", paramIn.getString("imageUuid"));
		Result result = imageCore.showImageScanResult(paramIn);
		return result;
	}
	@Override
	public Result getTask(Integer taskId) {
		try {
			Task task = taskMapper.getTaskDetail(taskId);
			if(null==task){
				return new Result(false,"查询任务详情结果为空");
			}
			JSONObject taskObject = JSONObject.parseObject(JSONObject.toJSONString(task));
			//查询pipeline阶段jenkins构建任务对象
			TaskEvent jenkinsBuildJobEvent = new TaskEvent(task.getTaskId(), Constant.JENKINS_STEP);
			jenkinsBuildJobEvent = taskEventMapper.selectEventsByTaskIdAndStep(jenkinsBuildJobEvent);
			JSONObject jenkinsBuildJobObject = null;
			if(null!=jenkinsBuildJobEvent){
				jenkinsBuildJobObject =JSONObject.parseObject(JSONObject.toJSONString(jenkinsBuildJobEvent));
			}
			taskObject.put("jenkinsBuildJobObject", jenkinsBuildJobObject);
			//查询pipeline阶段sonar质量分析任务对象
			TaskEvent sonarEvent = new TaskEvent(task.getTaskId(), Constant.SONAR_STEP);
			sonarEvent = taskEventMapper.selectEventsByTaskIdAndStep(sonarEvent);
			JSONObject sonarObject = null;
			if(null!=sonarEvent){
				sonarObject =JSONObject.parseObject(JSONObject.toJSONString(sonarEvent));
			}
			taskObject.put("sonarObject", sonarObject);
			//查询pipeline阶段应用包上传任务对象
			TaskEvent uploadAppEvent = new TaskEvent(task.getTaskId(), Constant.UPLOAD_APP_PACKAGE_STEP);
			uploadAppEvent = taskEventMapper.selectEventsByTaskIdAndStep(uploadAppEvent);
			JSONObject uploadAppObject = null;
			if(null!=uploadAppEvent){
				uploadAppObject =JSONObject.parseObject(JSONObject.toJSONString(uploadAppEvent));
			}
			taskObject.put("uploadAppObject", uploadAppObject);
			//查询pipeline阶段镜像制作任务对象
			TaskEvent makeImageEvent = new TaskEvent(task.getTaskId(), Constant.MAKE_IMAGE_STEP);
			makeImageEvent = taskEventMapper.selectEventsByTaskIdAndStep(makeImageEvent);
			JSONObject makeImageObject = null;
			if(null!=makeImageEvent){
				makeImageObject =JSONObject.parseObject(JSONObject.toJSONString(makeImageEvent));
			}
			taskObject.put("makeImageObject", makeImageObject);
			//查询pipeline阶段上传任务对象
			TaskEvent uploadImageEvent = new TaskEvent(task.getTaskId(), Constant.UPLOAD_IMAGE_STEP);
			uploadImageEvent = taskEventMapper.selectEventsByTaskIdAndStep(uploadImageEvent);
			JSONObject uploadImageObject = null;
			if(null!=uploadImageEvent){
				uploadImageObject =JSONObject.parseObject(JSONObject.toJSONString(uploadImageEvent));
			}
			taskObject.put("uploadImageObject", uploadImageObject);
			//查询pipeline阶段镜像扫描任务对象
			TaskEvent clairScannerEvent = new TaskEvent(task.getTaskId(), Constant.CLAIR_STEP);
			clairScannerEvent = taskEventMapper.selectEventsByTaskIdAndStep(clairScannerEvent);
			JSONObject clairScannerObject = null;
			if(null!=clairScannerEvent){
				clairScannerObject =JSONObject.parseObject(JSONObject.toJSONString(clairScannerEvent));
			}
			taskObject.put("clairScannerObject", clairScannerObject);
			//查询pipeline阶段镜像推送任务对象
			TaskEvent pushImageEvent = new TaskEvent(task.getTaskId(), Constant.PUSH_IMAGE_STEP);
			pushImageEvent = taskEventMapper.selectEventsByTaskIdAndStep(pushImageEvent);
			JSONObject pushImageObject = null;
			if(null!=pushImageEvent){
				pushImageObject =JSONObject.parseObject(JSONObject.toJSONString(pushImageEvent));
			}
			taskObject.put("pushImageObject", pushImageObject);
			return new Result(true, taskObject, "success");
		} catch (SQLException e) {
			LOGGER.error("Query task info fail:"+e.getMessage());
			return new Result(false, "查询任务详情失败:"+e.getMessage());
		}
	}
	@Override
	public Result deleteTask(Integer taskId) {
		try {
			int i = taskMapper.deleteTask(taskId);
			if(i==1){
				return new Result(true, "success");
			}else{
				return new Result(false, "删除任务执行异常");
			}
		} catch (SQLException e) {
			LOGGER.error("Delete task info fail:"+e.getMessage());
			return new Result(false, "删除任务失败:"+e.getMessage());
		}
	}
	/**
	 * 
	* @Title: createTaskEvent 
	* @Description: 任务执行事件 
	* @param     设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private void createTaskEvent(String eventName,String eventResult,int taskId, int excuteTimes,
			long eventTimeUsed,String messageInfo,byte eventStep){
		try {
			int executeTimes = 1;
			TaskEvent taskEvent = new TaskEvent();
			//如果是jenkins构建过程，写入jenkins的构建次数；其他过程通过字增加一次
			if(eventStep==Constant.JENKINS_STEP){
				executeTimes = excuteTimes;
			}else{
				taskEvent.setTaskId(taskId);
				taskEvent.setEventStep(eventStep);
				taskEvent = taskEventMapper.selectEventsByTaskIdAndStep(taskEvent);
				if(null!=taskEvent){
					executeTimes = taskEvent.getExcuteTimes()+1;
				}
			}
			Task task = taskMapper.getTaskDetail(taskId);
			if(null!=task){
				taskEvent = new TaskEvent(eventName, taskId, eventResult, executeTimes,
						eventTimeUsed, messageInfo,eventStep,task.getTaskCreator());
				taskEventMapper.insertTaskEvent(taskEvent);
			}
		} catch (SQLException e) {
			LOGGER.error("create task event fail");
		}
	}
	/**
	 * 
	* @Title: createRepositoryItem 
	* @Description: 创建任务子项 
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	private Result createRepositoryItem(JSONObject paramIn){
		int taskId = paramIn.getIntValue("taskId");
		LOGGER.info("Create Jenkins project job begin...");
		publisher.pushMessage(paramIn.getInteger("taskId"), "1");
		long begin = new Date().getTime()/1000;
		Result result = this.createRepository(paramIn);
		long end = new Date().getTime()/1000;
		LOGGER.info("Create Jenkins project job end. Lost time "+(end-begin)+"s");
		if(!result.isSuccess()){
			return result;
		}
		this.createTaskEvent(Constant.REPOSITORY_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				taskId,0,end-begin, result.getData()==null?null:result.getData().toString(),Constant.REPOSITORY_STEP);
		return result;
	}
	@Override
	public Result startTask(JSONObject paramIn) {
		//镜像对象
		ImageModel imageModel = new ImageModel();
		int taskStage = paramIn.getIntValue("taskStage");
		//如果只执行安全扫描或者镜像推送步骤，需要提供镜像imageUuid、imageName、imageTag
		String imageUuid = paramIn.getString("imageUuid");
		String imageName = paramIn.getString("imageName"); 
    	String imageTag = paramIn.getString("imageTag");
		Result result = new Result();
		int taskId = paramIn.getInteger("taskId");
		Task task = null;
		try {
			task = taskMapper.getTaskDetail(taskId);
			if(null==task){
				LOGGER.error("未查到相关任务");
				return new Result(false, "未查到相关任务");
			}
			//更新构建次数
			task.setBuildTimes(task.getBuildTimes()+1);
			task.setLastBuildTime(new Date());
			taskMapper.updateTask(task);
		} catch (SQLException e) {
			LOGGER.error("查询任务信息异常："+e.getMessage());
			return new Result(false,"查询任务信息异常："+e.getMessage());
		}
		paramIn = JSONObject.parseObject(JSONObject.toJSONString(task));
		paramIn.put("newImage", Status.JUDGE.NO.ordinal());
		imageModel.setDeployStatus((byte)Status.JUDGE.NO.ordinal());
		paramIn.put("clairStatus", Status.IMAGE_SCANNER.FAIL.ordinal());
		imageModel.setImageScanStatus((byte)Status.IMAGE_SCANNER.FAIL.ordinal());
		paramIn.put("imageType", Type.IMAGE.APPLICATION.name());
		imageModel.setImageType(Type.IMAGE.APPLICATION.name());
		imageModel.setProjectId(task.getProjectId());
		imageModel.setRegistryId(task.getRegistryId());
		imageModel.setImageCreator(task.getTaskCreator());
		imageModel.setEnvId(task.getEnvId());
		if(taskStage==Constant.PIPELINE_RUN){//按顺序执行
			//从应用构建开始
			if(task.getTaskStage()<=Constant.JENKINS_STEP){
				result = this.jenkinsJobBuild(paramIn);
				if(!result.isSuccess()){
					return result;
				}
				//执行代码质量分析
				if(task.getSonarEnable()==Status.JUDGE.YES.ordinal()){
				}
				//是否在jenkins中制作镜像
				if(task.getBuildImageInJenkins()==Status.JUDGE.YES.ordinal()){
				}else{
					net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(result.getData());
					paramIn.put("imageName",task.getJenkinsJobName());
					paramIn.put("imageTag", object.getString("number"));
					result = this.makeImage(paramIn);
					if(!result.isSuccess()){
						return result;
					}
				}
				//是否在jenkins中执行推送镜像到仓库
				if(task.getPushImageInJenkins()==Status.JUDGE.YES.ordinal()){
					
				}else{
					JSONObject object = JSONObject.parseObject(result.getData().toString());
					paramIn.put("imageUuid", object.getString("imageUuid"));
					paramIn.put("imageName", object.getString("imageName"));
					paramIn.put("imageTag", object.getString("imageTag"));
					paramIn.put("registryUrl", task.getRegistryUrl());
					result = this.pushImage(paramIn);
					if(!result.isSuccess()){
						return result;
					}else{
						paramIn.put("newImage", Status.JUDGE.YES.ordinal());
					}
				}
			}else if(task.getTaskStage()==Constant.UPLOAD_APP_PACKAGE_STEP){//从应用包上传开始
				//1.执行镜像制作镜像
				result = this.makeImage(paramIn);
				//2.镜像推送到仓库
				JSONObject object = JSONObject.parseObject(result.getData().toString());
				paramIn.put("imageUuid", object.getString("imageUuid"));
				paramIn.put("imageName", object.getString("imageName"));
				paramIn.put("imageTag", object.getString("imageTag"));
				paramIn.put("registryUrl", task.getRegistryUrl());
				result = this.pushImage(paramIn);
				if(!result.isSuccess()){
					return result;
				}else{
					paramIn.put("newImage", Status.JUDGE.YES.ordinal());
				}
			}else if(task.getTaskStage()==Constant.UPLOAD_IMAGE_STEP){//从镜像包上传开始
				//1.docker load镜像
				this.loadImage(paramIn);
				//2.镜像推送到仓库
				result = this.pushImage(paramIn);
				if(!result.isSuccess()){
					return result;
				}else{
					paramIn.put("newImage", Status.JUDGE.YES.ordinal());
				}
			}
			//是否执行镜像安全扫描
			if(task.getClairEnable()==Status.JUDGE.YES.ordinal()){
				result = this.clairScanner(paramIn);
				if(result.isSuccess()){
					paramIn.put("clairStatus", Status.IMAGE_SCANNER.SUCCESS.ordinal());
					imageModel.setImageScanStatus((byte)Status.IMAGE_SCANNER.SUCCESS.ordinal());
				}else{
					paramIn.put("clairStatus", Status.IMAGE_SCANNER.FAIL.ordinal());
					imageModel.setImageScanStatus((byte)Status.IMAGE_SCANNER.FAIL.ordinal());
				}
			}
		//单个步骤执行
		}else if(taskStage==Constant.JENKINS_STEP){//应用构建执行
			result = this.jenkinsJobBuild(paramIn);
		}else if(taskStage==Constant.UPLOAD_APP_PACKAGE_STEP){//应用包上传执行
			return new Result(false, "不支持单独执行此步骤");
//			this.createUploadAppItem();
		}else if(taskStage==Constant.MAKE_IMAGE_STEP){//镜像制作执行
			if(task.getTaskStage()<Constant.MAKE_IMAGE_STEP){
				TaskEvent uploadApp = new TaskEvent(taskId, Constant.UPLOAD_APP_PACKAGE_STEP);
				boolean uploadAppStage = taskExcuteStageEnable(uploadApp);
				TaskEvent jenkinsBuild = new TaskEvent(taskId, Constant.JENKINS_STEP);
				boolean jenkinsBuildStage = taskExcuteStageEnable(jenkinsBuild);
				if(uploadAppStage||jenkinsBuildStage){
					result = this.makeImage(paramIn);
				}else{
					return new Result(false, "上一步骤执行失败或者未执行，不能执行当前操作");
				}
			}else{
//				result = this.createMakeImageItem();
			}
		}else if(taskStage==Constant.UPLOAD_IMAGE_STEP){//镜像上传执行
			return new Result(false, "不支持单独执行此步骤");
//			result = this.createUploadImageItem();
		}else if(taskStage==Constant.CLAIR_STEP){//执行镜像安全扫描
			if(task.getTaskStage()<Constant.MAKE_IMAGE_STEP){
				TaskEvent uploadImage = new TaskEvent(taskId, Constant.UPLOAD_IMAGE_STEP);
				boolean uploadImageStage = taskExcuteStageEnable(uploadImage);
				TaskEvent makeImage = new TaskEvent(taskId, Constant.MAKE_IMAGE_STEP);
				boolean makeImageStage = taskExcuteStageEnable(makeImage);
				if(uploadImageStage||makeImageStage){
					return this.clairScanner(paramIn);
				}else{
					return new Result(false, "上一步骤执行失败或者未执行，不能执行当前操作");
				}
			}else{
				return this.clairScanner(paramIn);
			}
			
		}else if(taskStage==Constant.PUSH_IMAGE_STEP){
			if(task.getTaskStage()<Constant.MAKE_IMAGE_STEP){
				TaskEvent uploadImage = new TaskEvent(taskId, Constant.UPLOAD_IMAGE_STEP);
				boolean uploadImageStage = taskExcuteStageEnable(uploadImage);
				TaskEvent makeImage = new TaskEvent(taskId, Constant.MAKE_IMAGE_STEP);
				boolean makeImageStage = taskExcuteStageEnable(makeImage);
				if(uploadImageStage||makeImageStage){
					result = this.pushImage(paramIn);
					if(!result.isSuccess()){
						return result;
					}else{
						paramIn.put("newImage", Status.JUDGE.YES.ordinal());
					}
				}else{
					return new Result(false, "上一步骤执行失败或者未执行，不能执行当前操作");
				}
			}else{
				result = this.pushImage(paramIn);
				if(!result.isSuccess()){
					return result;
				}else{
					paramIn.put("newImage", Status.JUDGE.YES.ordinal());
				}
			}
		}
		if(result.isSuccess()){
			String registryUrl = paramIn.getString("registryUrl");
	    	if(StringUtils.isEmpty(registryUrl)){
	    		return new Result(false, "仓库地址不能为空");
	    	}else{
	    		registryUrl = registryUrl.replace("http://", "").replace("https://", "");
	    		registryUrl = registryUrl.endsWith("/")?registryUrl.substring(0,registryUrl.lastIndexOf("/")):registryUrl;
	    	}
	    	imageModel.setImageName(registryUrl+"/"+paramIn.getString("imageName"));
			imageModel.setImageTag(paramIn.getString("imageTag"));
			imageModel.setImageUuid(paramIn.getString("imageUuid"));
			paramIn.put("imageModel", imageModel);
			LOGGER.info("Task successfully executed.");
			return new Result(true,paramIn, "执行成功");
		}
		return result;
	}
	@Override
	public Result uploadAppItem(JSONObject paramIn){
		int taskId = paramIn.getIntValue("taskId");
		long begin = new Date().getTime()/1000;
		Result result = null;
		if(!result.isSuccess()){
			return result;
		}
		long end = new Date().getTime()/1000;
		this.createTaskEvent(Constant.UPLOAD_APP_PACKAGE_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				taskId,0,end-begin, result.getData()==null?null:result.getData().toString(),Constant.UPLOAD_APP_PACKAGE_STEP);
		return result;
	}
	@Override
	public Result uploadImageItem(JSONObject paramIn){
		int taskId = paramIn.getIntValue("taskId");
		long begin = new Date().getTime()/1000;
		Result result = null;
		if(!result.isSuccess()){
			return result;
		}
		long end = new Date().getTime()/1000;
		this.createTaskEvent(Constant.UPLOAD_IMAGE_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				taskId,0,end-begin, result.getData()==null?null:result.getData().toString(),Constant.UPLOAD_IMAGE_STEP);
		return result;
	}
	/**
	* @Title: pushImage 
	* @Description: 推送仓库
	* @param @param paramIn{imageName}
	* @param @return    设定文件 
	* @return Result    返回类型 
	* @throws
	 */
	@Override
	public Result pushImage(JSONObject paramIn){
		paramIn.put("pipelineHostIp", systemConfig.getPipelineHostIp());
		paramIn.put("pipelineHostUser", systemConfig.getPipelineHostUser());
		paramIn.put("pipelineHostPwd", systemConfig.getPipelineHostPwd());
		int taskId = paramIn.getIntValue("taskId");
		LOGGER.info("Push image to registry begin...");
		publisher.pushMessage(paramIn.getInteger("taskId"), "8");
		long begin = new Date().getTime()/1000;
		Result result = imageCore.pushImage(paramIn);
		long end = new Date().getTime()/1000;
		LOGGER.info("Push image to registry end. Lost time "+(end-begin)+"s");
		if(!result.isSuccess()){
			return result;
		}
		this.createTaskEvent(Constant.PUSH_IMAGE_STEP_CHN,result.isSuccess()?Constant.SUCCESS_CHN:Constant.FAIL_CHN,
				taskId,0,end-begin, result.getData()==null?null:result.getData().toString(),Constant.PUSH_IMAGE_STEP);
		/*
		 * 镜像上传成功后，保存到镜像表
		 */
//		this.saveImageInfo(paramIn);
		return result;
	}
	private Result saveImageInfo(JSONObject paramIn){
		try {
			Task task = taskMapper.getTaskDetail(paramIn.getInteger("taskId"));
			if(null!=task){
				Image record = new Image();
				record.setImageUuid(paramIn.getString("imageUuid"));
				record.setImageName(paramIn.getString("imageName"));
				record.setImageTag(paramIn.getString("imageTag"));
				record.setProjectId(task.getProjectId());
				if(task.getClairEnable()==Status.JUDGE.YES.ordinal()){
					String clairlogsPath = systemConfig.getImageClairLogsPath()+
							"/scanner_result_" + paramIn.getString("imageUuid") + ".txt";
					record.setImageScanPath(clairlogsPath);
					TaskEvent taskEvent= new TaskEvent(task.getTaskId(), Constant.CLAIR_STEP);
					taskEvent = taskEventMapper.selectEventsByTaskIdAndStep(taskEvent);
					if(null==taskEvent){
						record.setImageScanStatus((byte)Status.IMAGE_SCANNER.NO.ordinal());
					}else{
						if(taskEvent.getEventResult().equals(Constant.SUCCESS_CHN)){
							record.setImageScanStatus((byte)Status.IMAGE_SCANNER.SUCCESS.ordinal());
						}else{
							record.setImageScanStatus((byte)Status.IMAGE_SCANNER.FAIL.ordinal());
						}
						
					}
				}
				record.setImageStatus((byte)Status.IMAGE.NORMAL.ordinal());
				record.setImageCreator(paramIn.getInteger("taskCreator"));
				record.setRegistryId(paramIn.getInteger("registryId"));
				imageMapper.insertImage(record);
				return null;
			}else{
				return null;
			}
		} catch (SQLException e1) {
			return null;
		}
	}
	@Override
	public Result getTaskByProjectId(Integer projectId) {
		try {
			Task task = taskMapper.getTaskByProjectId(projectId);
			if(null==task){
				return new Result(true, "此项目没有执行的任务");
			}
			Result result = this.getTask(task.getTaskId());
			return result;
		} catch (SQLException e) {
			return new Result(false, "异常信息："+e.getMessage());
		}
	}
	private Result loadImage(JSONObject paramIn){
		
		return new Result(true, "");
	}
	/**
	* @Title: taskExcuteStageEnable 
	* @Description: 检查当前步骤是否可执行
	* @param @param taskEvent
	* @param @return    设定文件 
	* @return boolean    返回类型 
	* @throws
	 */
	private boolean taskExcuteStageEnable(TaskEvent taskEvent){
		try {
			taskEvent = taskEventMapper.selectEventsByTaskIdAndStep(taskEvent);
			if(null==taskEvent||taskEvent.getEventResult().equals(Constant.FAIL_CHN)){
				return false;
			}
			return true;
		} catch (SQLException e) {
			return false;
		}
	}
	@Override
	public GridBean getApplications(TaskModel taskModel) {
		int page = taskModel.getPage();
		int rows = taskModel.getRows();
		int totalpage = 0;
		Long totalNum = 0l;
		Page<Task> pageObject = new Page<Task>();
		try {
			Task task =new Task();
			task.setTaskStatus((byte)Status.COMMON.NORMAL.ordinal());
			task.setEnvId(taskModel.getEnvId());
			task.setProjectName(taskModel.getProjectName());
	        PageHelper.startPage(page, rows);
			List<Task> tasks = taskMapper.selectTaskList(task);
			for(Task temp: tasks){
				pageObject.add(temp);
			}
			totalpage = ((Page<?>) tasks).getPages();
			totalNum = ((Page<?>) tasks).getTotal();

		} catch (SQLException e) {
			LOGGER.error("批量查询构建应用失败:"+e.getMessage());
		}
		GridBean gridBean = new GridBean(page, totalpage, totalNum.intValue(), pageObject);
		return gridBean;
	}
}
